package com.lx.javasunmmrize.proxy.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Description cglib代理:不需要实现接口,页属于动态代理范畴
 * @Author lx
 * @Date 2021/2/28 20:47
 **/
public class CglibProxy implements MethodInterceptor{
    Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }


    //返回一个代理对象
    public Object getProxyInstance(){
        //1.创建一个工具类
        Enhancer enhancer = new Enhancer();
        //2.将被代理类设置为父类
        enhancer.setSuperclass(target.getClass());
        //3.设置回调函数,此处为自己
        enhancer.setCallback(this);
        //4.创建代理对象
        return  enhancer.create();

    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("cglib代理开始======");
        Object res = method.invoke(target, objects);
        System.out.println("cglib代理开始======");
        return res;
    }
}
